package cn.juque.jdfsystem.task;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.PrimitiveArrayUtil;
import cn.juque.common.constants.StringConstants;
import cn.juque.common.constants.YesOrNoEnum;
import cn.juque.common.utils.HttpClientUtil;
import cn.juque.common.utils.dto.GetDTO;
import cn.juque.jdfsystem.domain.FileInfoDO;
import cn.juque.jdfsystem.enums.ConfigCodeEnum;
import cn.juque.jdfsystem.helper.FileInfoHelper;
import cn.juque.jdfsystem.helper.RegisterInfoHelper;
import cn.juque.jdfsystem.mapper.FileInfoMapper;
import cn.juque.jdfsystem.service.IFileInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * @author juque
 * @version 1.0.0
 * <ul>
 *     <li>CheckFileExistsTask</li>
 * </ul>
 * @date 2023-01-18 09:05:59
 **/
@Slf4j
@Service("checkFileExistsTask")
public class CheckFileExistsTask extends AbstractTask {

    @Resource
    private FileInfoMapper fileInfoMapper;

    @Resource
    private FileInfoHelper fileInfoHelper;

    @Resource
    private IFileInfoService fileInfoService;

    @Resource
    private RegisterInfoHelper registerInfoHelper;

    /**
     * 任务逻辑
     *
     * @param args 参数
     */
    @Override
    public void execute(String[] args) {
        String value = super.configInfoHelper.getConfigValue(ConfigCodeEnum.CHECK_FILE_LIMIT_DAY.getCode());
        if (CharSequenceUtil.isEmpty(value)) {
            return;
        }
        int day = Integer.parseInt(value);
        // 盘点前一天
        Date maxDate = DateUtil.offsetDay(new Date(), -1);
        Date minDate = DateUtil.offsetDay(maxDate, -day);
        FileInfoDO query = new FileInfoDO();
        query.setCreateDateBegin(DateUtil.format(minDate, DatePattern.PURE_DATE_PATTERN));
        query.setCreateDateEnd(DateUtil.format(maxDate, DatePattern.PURE_DATE_PATTERN));
        List<FileInfoDO> fileList = this.fileInfoMapper.queryInfoList(query);
        fileList.stream()
                .filter(f-> YesOrNoEnum.YES.getCode().equals(f.getValidFlag()))
                .forEach(f -> {
            File file = this.fileInfoHelper.getFile(f);
            if (FileUtil.exist(file)) {
                return;
            }
            //下载文件
            byte[] byteArray = this.downloadFile(f.getId());
            if (PrimitiveArrayUtil.isNotEmpty(byteArray)) {
                this.fileInfoService.saveFile(f, byteArray);
            }
        });

    }

    /**
     * 设置随机休眠等待最大时长 单位：秒
     *
     * @return 秒
     */
    @Override
    protected Integer initSleepTimes() {
        return null;
    }

    /**
     * 文件下载
     *
     * @param fileId 文件ID
     * @return 文件流
     */
    private byte[] downloadFile(String fileId) {
        List<String> ipList = this.registerInfoHelper.getValidOtherIp();
        for (String ip : ipList) {
            try {
                String url = StringConstants.HTTP + ip + "/jdf/file/view/" + fileId + "?ignore=true";
                GetDTO getDTO = new GetDTO(url, null, null, null);
                return HttpClientUtil.download(getDTO);
            } catch (Exception e) {
                log.warn("ip:{}未能找到文件:{}", ip, fileId);
            }
        }
        return new byte[0];
    }

    @Override
    protected String getTaskName() {
        return "CheckFileExistsTask";
    }
}
